package com.eco.fanliapp.admin.security;


import com.eco.fanliapp.entity.Administrator;
import com.eco.fanliapp.admin.security.filter.JWTAuthenticationFilter;
import com.eco.fanliapp.admin.security.filter.JWTLoginFilter;
import com.eco.fanliapp.admin.security.handler.CustomAccessDeniedHandler;
import com.eco.fanliapp.service.IAdministratorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.LogoutConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * SpringSecurity的配置
 * 通过SpringSecurity的配置，将JWTLoginFilter，JWTAuthenticationFilter组合在一起
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private IAdministratorService administratorService;
    /**
     * 需要放行的URL
     */
    private static final String[] AUTH_WHITELIST = {
            "/web/order/manualPayOrder",//手动操作订单
            "/web/administrator/createVerifyCode",//后台验证码
            "/web/administrator/login",//后台登录
            "/mobile/home/money/tutorial",//三步省钱
            "/mobile/home/kingKong/list",//金刚眼模块
            "/mobile/home/kingKongSon/list",//金刚眼模块
            "/mobile/home/banner/list",//首页三个banner模块
            "/mobile/login/loginOnOff",//登录界面开关
            "/web/administrator/register",
            "/mobile/login/codeLogin",//验证码登录
            "/mobile/login/getUserInfo",//微信登录
            "/mobile/login/getCode",//获取验证码
            "/mobile/login/phonecheckWX",//手机登录后绑定微信
            "/mobile/login/WXcheckphone",//微信登录后绑定手机
            "/mobile/home/getHdkSearchItemIdDetail",//单品详情
            "/mobile/home/getSimilarInfo2",//猜你喜欢
            "/mobile/home/getFriends",//朋友圈列表
            "/mobile/home/getGoodsScheme",
            "/mobile/home/getFriendsCount",//朋友圈分享次数增加
            "/mobile/home/shareGoods",//朋友圈分享次数增加
            "/mobile/goodsFree/findAllGoodsFree",//免單商品查詢
            "/mobile/goodsFree/checkHaveBuy",//查詢是否購買過商品
            "/mobile/home/getClassify",//获取首页分类
            "/mobile/home/getHotKey",//获取热词
            "/mobile/home/dtk/hotSearch",//大淘客热搜词
            "/mobile/home/dtk/shopMessage",//大淘客店铺搜索
            "/mobile/home/getSuperClassify",//超级分类
            "/mobile/home/getSuperCategory",//大淘客超级分类
            "/mobile/img/getPoster",//获取朋友圈广告位
            "/mobile/img/advertisingPopup",//广告弹唱
            "/mobile/img/getInvitationPoster",//邀请海报
            "/mobile/img/getInvitationPosterUrl",//邀请链接
            "/mobile/img/findByPicTypeThree",//启动页图
            "/mobile/img/findByPicTypeFive",//站内弹窗图
            "/mobile/img/findByPicTypeFour",//首页图
            "/mobile/home/SearchKey",//关键词搜索
            "/mobile/home/getClassifyItemList",//根据首页类目查询商品列表
            "/mobile/home/getGoodsFreeList",//查询免单商品
            "/mobile/home/getPopup",//首页弹窗
            "/mobile/home/getPopupSearch",//首页弹窗
            "/web/withdrawal/findAll",//跑马灯
            "/mobile/reward/getNotLoginRedMoney",//未登录红包金额
            "/mobile/home/SearchSuperTitle",//超级搜索
            "/mobile/home/getDTKSearch",//大淘客搜索
            "/mobile/home/SearchLocalGoods",//搜索本地商品
            "/mobile/home/TaobaoAnalyzeTkl",//解析淘口令
            "/code/getkey",//淘宝授权回调地址
            "/mobile/v/version",//app版本号查询
            "/wx/**",//微信分享、授权相关
            "/img/**", //邀请海报
            "/app/taobao/auth",//授权渠道id
            "/app/taobao/auth/url",//获取授权渠道id的URL
            "/app/user/appGoods/hitCount",//商品点击数
            "/mobile/home/getSaleslist",//获取榜单商品
            "/syapp/syxy", //省鸭协议
            "/syapp/spjc", //视频教程
            "/syapp/btxz", //补贴须知
            "/syapp/yqzq", //邀请赚钱
            "/syapp/gl", //攻略
            "/syapp/kf", //客服
            "/resources/**",//静态资源放行
            "/static/**",//静态资源放行
            "/audio/**",//静态资源放行
            "/css/**",//静态资源放行
            "/js/**",//静态资源放行
            "/syapp/kfzjtx",//我的客服
            "/syapp/kffxyl",//我的客服
            "/syapp/kfspzx",//我的客服
            "/syapp/kfxszn",//我的客服
            "/syapp/rmwt01",//我的客服
            "/syapp/rmwt02",//我的客服
            "/syapp/rmwt03",//我的客服
            "/syapp/rmwt04",//我的客服
            "/syapp/rmwt05",//我的客服
            "/syapp/rmwt06",//我的客服
            "/favicon.ico",//静态资源放行
            "/feedback/getopinion",//意见反馈
            "/mobile/login/getPhoneLoginSwitch",//手机登录开关
            "/web/appGoods/addAppGoodsFromQq",//添加商品
            "/mobile/goodsCommend/list",//商品详情页推荐商品
            "/druid/**",//商品详情页推荐商品
            "/web/appGoods/out",//商品拉取接口
            "/web/appGoods/getDownItems",//商品失效接口
            "/web/appGoods/updateItem",//商品更新接口
            "/web/order/manualRedMoneyNow",//设置红包到期日期为当前
            "/web/order/manualPayOrder",//手动的调用一次付款订单拉取定时任务
            "/web/order/manualFailOrder",//手动的调用一次失效订单拉取定时任务
            "/web/order/manualOrder",//手动的调用一次结算订单拉取定时任务
            "/mobile/home/getClassifyGoodsList",//商品列表
            "/mobile/home/getRecommendGoods",//商品推荐列表
            "/app/syTimePeriod/homePageList",//app秒杀商品首页
            "/app/syTimePeriod/list",//app秒杀商品首页
            "/app/syTimePeriodGoods/list",//app秒杀商品首页
            "/web/presell/order/import",//预售订单修改佣金
            "/web/taolijin/insertTljGoodsfree",//新增淘礼金商品
            "/web/taolijin/ishasItemId"//判断商品今天是否已经添加 --淘礼金项目使用
    };


    /**
     * 根据用户名，到数据库查询该用户（）
     *
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            log.info("====>前端输入的username{}", username);
            Administrator users = administratorService.findByAdministratorName(username);
            if (users == null) {
                throw new UsernameNotFoundException("用户名或密码错误");
            }
            String password = users.getAdminitratorPassword();
            //spring security 版本在5.0后就要加个PasswordEncoder
            PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
            String passwordAfterEncoder = passwordEncoder.encode(password);
            //获取用户角色
            //获取用户对应权限
            return User.withUsername(username).password(passwordAfterEncoder).roles("").build();
        };

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        CustomAccessDeniedHandler c = new CustomAccessDeniedHandler();
        LogoutConfigurer<HttpSecurity> httpSecurityLogoutConfigurer =
                http.cors()
                        .and().csrf().disable()
                        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                        .authorizeRequests()
                        .antMatchers(AUTH_WHITELIST).permitAll()
                        .anyRequest().authenticated()  // 所有请求需要身份认证
                        .and()
                        .exceptionHandling().accessDeniedHandler(c) // 自定义访问失败处理器
                        .and()
                        .addFilter(new JWTLoginFilter(authenticationManager()))
                        .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                        .logout() // 默认注销行为为logout，可以通过下面的方式来修改
                        .logoutUrl("/logout")
                        .logoutSuccessUrl("/login")// 设置注销成功后跳转页面，默认是跳转到登录页面;
                        // .logoutSuccessHandler(customLogoutSuccessHandler)
                        .permitAll();

    }


}
